/*
实现选择操作
结果写入块从60开始
打印选择出的数据和IO次数
正确性已检验
*/

#include <stdlib.h>
#include <stdio.h>
#include "extmem.h"

int wf=60;
Buffer buf;
int wcount=0;
int writeData(char* Xp,char* Yp,int p,unsigned char *wblk);
// 实现目标：将17~48blk中的数据读出，选择其中C=130的元组，写入60开始的磁盘文件中
int main(int argc, char const *argv[])
{
    int countnum=0;
    unsigned char *rblk;
    unsigned char *wblk;
    int p=0;
    // static unsigned char *wblk;
    if (!initBuffer(520, 64, &buf))
    {
        perror("Buffer Initialization Failed!\n");
        return -1;
    }

    wblk=getNewBlockInBuffer(&buf);
    for (int rf = 17; rf < 49; rf++)
    {
        if ((rblk = readBlockFromDisk(rf, &buf)) == NULL)
        {
            perror("Reading Block Failed!\n");
            return -1;
        }

        int X = -1;
        int Y = -1;
        int addr = -1;
        char strX[5],strY[5];
        // printf("\nblock %d:\n",rf);
        for (int i = 0; i < 7; i++)
        {
            for (int k = 0; k < 4; k++)
            {
                strX[k] = *(rblk + i*8 + k);
            }
            X = atoi(strX);
            for (int k = 0; k < 4; k++)
            {
                strY[k] = *(rblk + i*8 + 4 + k);
            }
            Y = atoi(strY);
            // printf("(%d, %d) ", X, Y);
            if (X==130)
            {
                countnum++;
                p=writeData(strX,strY,p,wblk);
                printf("\nin block %d,X=%d,Y=%d\n",rf,X,Y);
            }
            
        }
        freeBlockInBuffer(rblk,&buf);
    }
    // 最后需要强制写入一下，将每天充满的block块写入
    // printf("\nforce write\n");
    if (writeBlockToDisk(wblk, wf++, &buf) != 0)
        {
            perror("Writing Block Failed!\n");
            exit(-1);
        }
    printf("\ntotal countNum:%d\n",countnum);
    printf("\ntotal IO %ld\n",buf.numIO);
    return 0;
}

int writeData(char* Xp,char* Yp,int p,unsigned char *wblk)
{
    if (p==56)
    {
        printf("write %d to the disk\n",++wcount);
        //将下一个块的指针存入p=57中，并将当前块的数据写入磁盘块中，清空当前块
        *(wblk+57)=(wf+1);
        if (writeBlockToDisk(wblk, wf++, &buf) != 0)
        {
            perror("Writing Block Failed!\n");
            exit(-1);
        }
        // 重新从0开始写数据，就相当于使用了free
        // api里的free相当于告知buf当前块已不再需要使用
        return 0;
    }
    int i=0;
    for (i = 0; i < 3; i++)
    {
        *(wblk+p)=*(Xp+i);
        p++;
    }
    // 似乎null直接用0填充就好了
    *(wblk+p)=(char)0;
    p++;
    for (i = 0; i < 4; i++)
    {
        *(wblk+p)=*(Yp+i);
        p++;
    }
    return p;
}
